# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'C0090': {
        # angela支付 微信扫码 3.8% 300-5000 dwc
        # angela支付 银联扫码 1.5% 20-5000 dwc
        # angela支付 银联快捷 1.5% 20-5000 dwc
        # angela支付 京东扫码 2.8% 10-5000 dwc
        # angela支付 支付宝扫码 3.3% 300-10000 dwc
        # angela支付 支付宝H5 3.3% 100-5000 dwc
        'API_KEY': '9HGTX0rwBT6CEoc008i9vy35llsHeXhi',
        'gateway': 'http://angtz.com/api/pay',
        'query_gateway': 'http://angtz.com/api/query',
    },
    'C0147': { # 支付宝原生H5红包3.2  微信4.2
        # angela支付 微信扫码 3.8% 300-5000 dwc
        # angela支付 银联扫码 1.5% 20-5000 dwc
        # angela支付 银联快捷 1.5% 20-5000 dwc
        # angela支付 京东扫码 2.8% 10-5000 dwc
        # angela支付 支付宝扫码 3.3% 300-10000 dwc
        # angela支付 支付宝H5 3.3% 100-5000 dwc
        'API_KEY': 'CSBIxfD8yHs4mj7aG8BktFKJqH4q1x30',
        'gateway': 'http://angtz.com/api/pay',
        'query_gateway': 'http://angtz.com/api/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k.lower(), parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("angelapay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'wechatscan':
        return 'wechat_qrcode'
    elif service == 'unionpayscan':
        return 'yl_qrcode'
    elif service == 'unionpayquick':
        return 'yl_nocard'
    elif service == 'jdscan':
        return 'jd_qrcode'
    elif service == 'alipayscan':
        return 'alipay_qrcode'
    elif service == 'alipayh5':
        return 'alipay_app'
    return 'wechat_qrcode'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = str(info['app_id'])
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('customerno', app_id),
        ('channeltype', _get_pay_type(service)),
        ('customerbillno', str(pay.id)),
        ('orderamount', '%.2f' % pay_amount),
        ('customerbilltime', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('notifyurl', '{}/pay/api/{}/angelapay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ip', _get_device_ip(info)),
        ('devicetype', 'wap'),
        ('customeruser', str(pay.user_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("angelapay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['customerbillno'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('angelapay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# OK
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("angelapay notify data: %s, order_id is: %s", data, data['customerbillno'])
    verify_notify_sign(data, api_key)
    pay_id = data['customerbillno']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('angelapay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['paystatus'])
    trade_no = str(data['orderno'])
    total_fee = float(data['orderamount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('angelapay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    dct = OrderedDict((
        ('customerNo', str(app_id)),
        ('customerBillNo', str(pay_id)),
    ))
    dct['sign'] = generate_sign(dct, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info('angelapay query data: %s, order_id is: %s', json.dumps(dct), dct['customerBillNo'])
    response = requests.post(_get_query_gateway(app_id), data=dct, headers=headers, timeout=3)
    _LOGGER.info('angelapay query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['PayStatus'])
        total_fee = float(data['OrderAmount'])
        trade_no = str(data['OrderNo'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == 'SUCCESS':
            _LOGGER.info('angelapay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('angelapay data error, status_code: %s', response.status_code)
